//ResponseTest.java
package com.ylaihui.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ResponseTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String characterEncoding = resp.getCharacterEncoding();
        System.out.println(characterEncoding);

        // 设置服务器的响应字符集为 UTF-8
        resp.setCharacterEncoding("UTF-8");
        //characterEncoding = resp.getCharacterEncoding();
        //System.out.println(characterEncoding);

        // 通过响应头，设置浏览器的字符集UTF-8，
        // 浏览器解析 响应消息的时候就使用了 UTF-8 字符集
        resp.setHeader("Content-Type", "text/html; charset=UTF-8");
        System.out.println(resp.getCharacterEncoding());
        PrintWriter writer = resp.getWriter();

        // 如果同时调用了两个流， 那么第二个调用的时候会报错。
        // java.lang.IllegalStateException: getWriter() has already been called for this response
        //ServletOutputStream outputStream = resp.getOutputStream();

        writer.write("猿来绘！！！！");
    }
}
